import logging
import shutil
import sys
from pathlib import Path

from PyQt5.QtWidgets import QApplication

from src.myapp import settings
from src.myapp.bootstrap_window import *
from src.myapp.main_panel import MainPanel

logger = logging.getLogger(__name__)

__version__ = settings.APP_VERSION


def main(cmd_args):
    # a proper app would use argparse, but we just do minimal argument
    # parsing to keep things simple
    pre_release_channel = None
    skip_confirmation = False
    while cmd_args:
        arg = cmd_args.pop(0)
        if arg in ['a', 'b', 'rc']:
            pre_release_channel = arg
        else:
            skip_confirmation = arg == 'skip'

    # The app must ensure dirs exist
    for dir_path in [settings.INSTALL_DIR, settings.METADATA_DIR, settings.TARGET_DIR]:
        dir_path.mkdir(exist_ok=True, parents=True)

    # The app must be shipped with a trusted "root.json" metadata file,
    # which is created using the tufup.repo tools. The app must ensure
    # this file can be found in the specified metadata_dir. The root metadata
    # file lists all trusted keys and TUF roles.
    if not settings.TRUSTED_ROOT_DST.exists():
        # print("*****")
        # print(settings.TRUSTED_ROOT_SRC)
        # settings.TRUSTED_ROOT_SRC = 'C:\\Users\Jiang\AppData\Local\Programs\my_app\_internal\\root.json'
        # TODO 删除路径多余的部分 \src
        # settings.TRUSTED_ROOT_SRC = Path(settings.TRUSTED_ROOT_SRC.__str__().replace("\src", ""))

        root_src = Path(settings.TRUSTED_ROOT_SRC.__str__().replace("\src", ""))

        shutil.copy(src=root_src, dst=settings.TRUSTED_ROOT_DST)
        logger.info('Trusted root metadata copied to cache.')

    # Download and apply any available updates
    # update(pre=pre_release_channel, skip_confirmation=skip_confirmation)

    # Do what the app is supposed to do
    print(f'Starting {settings.APP_NAME} {settings.APP_VERSION}...')
    ...
    print('Doing what the app is supposed to do...')
    ...

    # 显示窗口
    app = QApplication(sys.argv)
    window = BootstrapWindow()
    window.ui.show()

    # 启动时检查更新
    t = ThreadCheckUpdate()
    t.call_when_boot = True
    t.init_ui_signal.connect(window.show_check_update_window)
    t.update_ui_signal.connect(window.refresh_when_found)
    t.timeout_signal.connect(window.refresh_when_timeout)
    t.start()

    sys.exit(app.exec_())
